export function routeTo({
	                        link,
	                        params,
	                        events = {},
	                        type = 'navigateTo'
                        }) {
	let url;
	if (params) {
		url = "/pages/" + link + "/" + link + makeQuery(params);
	} else {
		url = "/pages/" + link + "/" + link;
	}


	if (link === 'approve') {
		wx.requestSubscribeMessage({
			tmplIds: [ 'IaFIgVI7qPQlBru8eje8y6DZE7z7PhxqBbGj4SDz39g' ],
			complete(res) {
				uni[type]({
					url: url,
					events: events,
					complete(e) {
						console.log(e)
					}
				})
			}
		})
	} else {
		uni[type]({
			url: url,
			events: events,
			complete(e) {
				console.log(e)
			}
		})
	}

}

Array.prototype.remove = function (val) {
	let index = this.indexOf(val);
	if (index > -1) {
		this.splice(index, 1);
	}
};

export function makeQuery(queryObject) {
	let query = [];
	Object.keys(queryObject).forEach(function (key) {
		query.push(key + '=' + queryObject[key])
	})
	return '?' + query.join('&')
}


export function lengthText(txtValue) {
	if (typeof txtValue != "string") {
		txtValue = "" + txtValue + "";
	}
	var cArr = txtValue.match(/[^\x00-\xff]/ig);
	return txtValue.length + (cArr == null ? 0 : cArr.length);
}


export function IsDate(str) {
	if (lengthText(str) > 0) {
		if (lengthText(str) > 10) {
			// 判断是否为日期 判断日期类型是否为YYYY-MM-DD格式的类型
			var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
			var r = str.match(reg);
			if (r == null) {
				return false;
			}
		} else {
			// 判断日期类型是否为YYYY-MM-DD hh:mm:ss格式的类型
			var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/;
			var r = str.match(reg);
			if (r == null) {
				return false;
			}
		}
	}

	return true;

}

export function IsNumber(string, sign) {
	var number;
	if (string == null)
		return false;
	if ((sign != null) && (sign != '-') && (sign != '+')) {
		alert('IsNumber(string,sign)的参数出错：\nsign为null或"-"或"+"');
		return false;
	}
	if (string.split(" ").length != 1) {
		return false;
	}

	number = new Number(string);
	if (isNaN(number)) {
		return false;
	} else if ((sign == null) || (sign == '-' && number < 0) ||
		(sign == '+' && number > 0)) {
		return true;
	} else
		return false;
}


//阿拉伯数字转换为简写汉字
export function arabia_To_SimplifiedChinese(numberValue) {
	var numberValue = new String(Math.round(numberValue * 100)); // 数字金额  
	var chineseValue = ""; // 转换后的汉字金额  
	var String1 = "零壹贰叁肆伍陆柒捌玖"; // 汉字数字  
	var String2 = "万仟佰拾亿仟佰拾万仟佰拾元角分"; // 对应单位  
	var len = numberValue.length; // numberValue 的字符串长度  
	var Ch1; // 数字的汉语读法  
	var Ch2; // 数字位的汉字读法  
	var nZero = 0; // 用来计算连续的零值的个数  
	var String3; // 指定位置的数值  
	if (len > 15) {
		alert("超出计算范围");
		return "";
	}
	if (numberValue == 0) {
		chineseValue = "零元整";
		return chineseValue;
	}
	String2 = String2.substr(String2.length - len, len); // 取出对应位数的STRING2的值  
	for (var i = 0; i < len; i++) {
		String3 = parseInt(numberValue.substr(i, 1), 10); // 取出需转换的某一位的值  
		if (i != (len - 3) && i != (len - 7) && i != (len - 11) && i != (len - 15)) {
			if (String3 == 0) {
				Ch1 = "";
				Ch2 = "";
				nZero = nZero + 1;
			} else if (String3 != 0 && nZero != 0) {
				Ch1 = "零" + String1.substr(String3, 1);
				Ch2 = String2.substr(i, 1);
				if (Ch2 == "分") {
					Ch1 = "零角" + String1.substr(String3, 1);
				}
				nZero = 0;
			} else {
				Ch1 = String1.substr(String3, 1);
				Ch2 = String2.substr(i, 1);
				nZero = 0;
			}
		} else { // 该位是万亿，亿，万，元位等关键位  
			if (String3 != 0 && nZero != 0) {
				Ch1 = "零" + String1.substr(String3, 1);
				Ch2 = String2.substr(i, 1);
				nZero = 0;
			} else if (String3 != 0 && nZero == 0) {
				Ch1 = String1.substr(String3, 1);
				Ch2 = String2.substr(i, 1);
				nZero = 0;
			} else if (String3 == 0 && nZero >= 3) {
				Ch1 = "";
				Ch2 = "";
				nZero = nZero + 1;
			} else {
				Ch1 = "";
				Ch2 = String2.substr(i, 1);
				nZero = nZero + 1;
			}
			if (i == (len - 11) || i == (len - 3)) { // 如果该位是亿位或元位，则必须写上  
				Ch2 = String2.substr(i, 1);
			}
		}
		chineseValue = chineseValue + Ch1 + Ch2;
	}
	if (numberValue.substr(numberValue.length - 2, numberValue.length) == "00") {
		chineseValue = chineseValue + "零角零分";
	} else {
		if (String3 == 0) { // 最后一位（分）为0时，加上“整”  
			chineseValue = chineseValue + "零分";
		}
	}
	return chineseValue;
}


export function chooseFile({
	                           success
                           }) {
	let main = plus.android.runtimeMainActivity();
	let Intent = plus.android.importClass("android.content.Intent");

	//
	let fileIntent = new Intent(Intent.ACTION_GET_CONTENT)
	//fileIntent.setType(“image/*”);//选择图片
	//fileIntent.setType(“audio/*”); //选择音频
	//fileIntent.setType(“video/*”); //选择视频 （mp4 3gp 是android支持的视频格式）
	//fileIntent.setType(“video/*;image/*”);//同时选择视频和图片
	fileIntent.setType("*/*"); //无类型限制
	fileIntent.addCategory(Intent.CATEGORY_OPENABLE);
	main.startActivityForResult(fileIntent, 1);
	// 获取回调
	main.onActivityResult = function (requestCode, resultCode, data) {
		let Activity = plus.android.importClass("android.app.Activity");
		let ContentUris = plus.android.importClass("android.content.ContentUris");
		let Cursor = plus.android.importClass("android.database.Cursor");
		let Uri = plus.android.importClass("android.net.Uri");
		let Build = plus.android.importClass("android.os.Build");
		let Environment = plus.android.importClass("android.os.Environment");
		let DocumentsContract = plus.android.importClass("android.provider.DocumentsContract");
		let MediaStore = plus.android.importClass("android.provider.MediaStore");
		// 给系统导入 contentResolver
		let contentResolver = main.getContentResolver()
		plus.android.importClass(contentResolver);
		// 返回路径
		let path = '';
		if (resultCode == Activity.RESULT_OK) {
			let uri = data.getData()
			if ("file" == uri.getScheme().toLowerCase()) { //使用第三方应用打开
				path = uri.getPath();
			}
			if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) { //4.4以后
				path = getPath(this, uri);
			} else { //4.4以下下系统调用方法
				path = getRealPathFromURI(uri)
			}
			// 回调
			success(path)
		}

		// 4.4 以上 从Uri 获取文件绝对路径
		function getPath(context, uri) {
			let isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
			let scheme = uri.getScheme().toLowerCase()
			if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
				// ExternalStorageProvider
				if (isExternalStorageDocument(uri)) {
					let docId = DocumentsContract.getDocumentId(uri);
					let split = docId.split(":");
					let type = split[0];
					// 如果是手机内部存储
					if ("primary" == type.toLowerCase()) {
						return Environment.getExternalStorageDirectory() + "/" + split[1];
					} else {
						return '/storage/' + type + "/" + split[1];
					}
				}
				// DownloadsProvider
				else if (isDownloadsDocument(uri)) {
					let id = DocumentsContract.getDocumentId(uri);
					let split = id.split(":");
					return split[1]
					// console.log(id)
					// let contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), id);
					// return getDataColumn(context, contentUri, null, null);
				}
				// MediaProvider
				else if (isMediaDocument(uri)) {
					let docId = DocumentsContract.getDocumentId(uri);
					let split = docId.split(":");
					let type = split[0];
					let contentUri = null;
					if ("image" == type.toLowerCase()) {
						contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
					} else if ("video" == type.toLowerCase()) {
						contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
					} else if ("audio" == type.toLowerCase()) {
						contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
					}
					let selection = "_id=?";
					let selectionArgs = [ split[1] ];
					return getDataColumn(context, contentUri, selection, selectionArgs);
				}
			}
			// MediaStore (and general)
			else if ("content" == scheme) {
				return getDataColumn(context, uri, null, null);
			}
			// File
			else if ("file" == scheme) {
				return uri.getPath();
			}
		}

		// 4.4 以下 获取 绝对路径
		function getRealPathFromURI(uri) {
			let res = null
			let proj = [ MediaStore.Images.Media.DATA ]
			let cursor = contentResolver.query(uri, proj, null, null, null);
			if (null != cursor && cursor.moveToFirst()) {
				;
				let column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				res = cursor.getString(column_index);
				cursor.close();
			}
			return res;
		}

		// 通过uri 查找出绝对路径
		function getDataColumn(context, uri, selection, selectionArgs) {
			let cursor = null;
			let column = "_data";
			let projection = [ column ];
			// let contentResolver = context.getContentResolver()
			// plus.android.importClass(contentResolver);
			cursor = contentResolver.query(uri, projection, selection, selectionArgs, null);
			if (cursor != null && cursor.moveToFirst()) {
				let column_index = cursor.getColumnIndexOrThrow(column);
				return cursor.getString(column_index);
			}
		}

		function isExternalStorageDocument(uri) {
			return "com.android.externalstorage.documents" == uri.getAuthority() ? true : false
		}

		function isDownloadsDocument(uri) {
			return "com.android.providers.downloads.documents" == uri.getAuthority() ? true : false
		}

		function isMediaDocument(uri) {
			return "com.android.providers.media.documents" == uri.getAuthority() ? true : false
		}
	}
}


export function dateFormat(fmt, date) {
	if (typeof date == "string") {
		date = stringToDate(date);
	}
	const obj = {
		'y': date.getFullYear(), // 年份，注意必须用getFullYear
		'M': date.getMonth() + 1, // 月份，注意是从0-11
		'd': date.getDate(), // 日期
		'q': Math.floor((date.getMonth() + 3) / 3), // 季度
		'w': date.getDay(), // 星期，注意是0-6
		'H': date.getHours(), // 24小时制
		'h': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 12小时制
		'm': date.getMinutes(), // 分钟
		's': date.getSeconds(), // 秒
		'S': date.getMilliseconds() // 毫秒
	};
	const week = [ '天', '一', '二', '三', '四', '五', '六' ];
	for (const i in obj) {
		fmt = fmt.replace(new RegExp(i + '+', 'g'), function (m) {
			var val = obj[i] + '';
			if (i === 'w') return (m.length > 2 ? '星期' : '周') + week[val];
			for (var j = 0, len = val.length; j < m.length - len; j++) val = '0' + val;
			return m.length === 1 ? val : val.substring(val.length - m.length);
		});
	}
	return fmt;
}

function stringToDate(str) {

	const tempStrs = str.split(" ");

	const dateStrs = tempStrs[0].split("-");

	const year = parseInt(dateStrs[0], 10);

	const month = parseInt(dateStrs[1], 10) - 1;

	const day = parseInt(dateStrs[2], 10);

	const timeStrs = tempStrs[1].split(":");

	const hour = parseInt(timeStrs[0], 10);

	const minute = parseInt(timeStrs[1], 10);

	const second = parseInt(timeStrs[2], 10);

	return new Date(year, month, day, hour, minute, second);

}


export function richTextUrl(url) {

	if (!url.includes('://')) {
		return `${ Config.BASE_URL }/mobile/downFileImgByHtmlEdit.action?imgServerUrl=${ url }`
	} else if (url.match(/(http):\/\/([^\/]+)/i)) {
		return url.replace(/(http):\/\/([^\/]+)/i, `${ Config.BASE_URL }/mobile/downFileImgByHtmlEdit.action?imgServerUrl=`)
	} else {
		return ''
	}
}


export function toTreeData(data, attr) {
	const list = JSON.parse(JSON.stringify(data))
	const result = []
	const map = {}

	if (!(list instanceof Array)) {
		return []
	}
	list.forEach(item => {
		item.id = item[attr.id]
		item.name = item[attr.name]
		item.children = [];
		map[item.id] = item
	})

	list.forEach(item => {
		const parent = map[item[attr.parendId]]
		if (parent) {
			item.delete = true
			parent.children.push(item)
		}
	})
	Object.keys(map).filter(e => !map[e].delete).forEach(e => result.push(map[e]))
	return {
		children: result
	}
}


export function claerBadge() {
	//#ifdef APP-PLUS
	if (plus.os.name.toLowerCase() == 'ios') {
		//导入ios UIApplication
		var UIApplication = plus.ios.import("UIApplication");
		var app = UIApplication.sharedApplication();
		//获取应用图标的数量
		var oldNum = app.applicationIconBadgeNumber();
		var newNum = oldNum - 1;
		//设置应用图标的数量
		plus.runtime.setBadgeNumber(newNum);
		//导入个推原生类
		var GeTuiSdk = plus.ios.importClass('GeTuiSdk');
		GeTuiSdk.setBadge(newNum);
	}
	//#endif
}


export function formatDateStr(date, fmt) {
	let ret;
	if(date){
		date = date.replace(/-/g, '/')
	}
	date = new Date(date);
	const opt = {
		'Y+': date.getFullYear()
			.toString(),
		'm+': (date.getMonth() + 1).toString(),
		'd+': date.getDate()
			.toString(),
		'H+': date.getHours()
			.toString(),
		'M+': date.getMinutes()
			.toString(),
		'S+': date.getSeconds()
			.toString(),
	};
	Object.keys(opt)
		.forEach((k) => {
			ret = new RegExp(`(${ k })`).exec(fmt);
			if (ret) {
				fmt = fmt.replace(ret[1], (ret[1].length === 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, '0')));
			}
		});
	return fmt;
}

export function closeGustureBack() {
	const pages = getCurrentPages();
	const page = pages[pages.length - 1];
	// #ifdef APP-PLUS
	var currentWebview = page.$getAppWebview();
	currentWebview.setStyle({ 'popGesture': 'none' });
	// #endif
}

export function openGustureBack() {
	const pages = getCurrentPages();
	const page = pages[pages.length - 1];
	// #ifdef APP-PLUS
	var currentWebview = page.$getAppWebview();
	currentWebview.setStyle({ 'popGesture': 'close' });
	// #endif
}

export function getBase64Code(path) {
	return new Promise((((resolve, reject) => {
		const bitmap = new plus.nativeObj.Bitmap("test"); //test标识谁便取
		// 从本地加载Bitmap图片
		bitmap.load(path, function () {
			resolve(bitmap.toBase64Data());
		}, function (e) {
			reject(e)
		});
	})))
}
